package com.ktjy.kuozhan;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;

public class SimpleFactory {
    private static HashMap<String, Object> map = new HashMap<String, Object>();

    static {
        try {
            // 1.创建解析器 new SAXReader()
            SAXReader sr = new SAXReader();
            // 2.解析xml read()
            Document document = sr.read("ch07/src/main/resources/bean.xml");
            // 3.获取根节点 getRootElement()
            Element root = document.getRootElement();
            // 4.获取多个标签
            List<Element> list = root.elements("bean");
            for (Element element : list) {
                //5.获取id属性和class属性
                String id = element.attributeValue("id");
                String className = element.attributeValue("class");
                //6.通过反射技术创建对象
                Class clazz = Class.forName(className);
                Object coffee = clazz.newInstance();
                //7.将id和对象存储到容器中
                map.put(id, coffee);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //根据id获取对象
    public static Object getBean(String id) {
        return map.get(id);
    }
}
